package org.bot.client.flow;

import com.alibaba.fastjson.JSONObject;
import org.bot.api.config.ClientConfig;

import java.util.LinkedHashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: 沧月
 * @Date: 2024/1/11 10:13
 * @Description: 这个容器满了的时候再添加一个元素进去，就会挤出最后一个
 */
public class FixedSizeContainer extends LinkedHashSet<FlowTask> {
    private final int maxSize;

    private static final ExecutorService taskPool = Executors.newFixedThreadPool(ClientConfig.getBotConfig().getMaxTask());

    public FixedSizeContainer(int maxSize) {
        super(maxSize);
        this.maxSize = maxSize;
    }

    @Override
    public boolean add(FlowTask e) {
        if (size() >= maxSize) {
            throw new RuntimeException(String.format("任务已经超过最大列队【%s】", maxSize));
        }
        taskPool.execute(e);
        final boolean stat = super.add(e);
        if (stat) {
            this.updateClientStatus(e, 0);
        }
        return stat;
    }

    public void removeTask(FlowTask e) {
        this.updateClientStatus(e, -1);
        super.remove(e);
    }

    public void updateClientStatus(FlowTask e, int v) {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) taskPool;
        int activeCount = threadPoolExecutor.getActiveCount();
        int backlog = threadPoolExecutor.getQueue().size();
        e.getFlowExecute().serverClientInfo.clientStatus(e.getClientId(),
                new JSONObject().fluentPut("queue", backlog)
                        .fluentPut("active", (activeCount + v)));
    }
}
